package com.sprouting.personal.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sprouting.personal.annotations.ApiIdempotent;
import com.sprouting.personal.interfaces.common.Constant;
import com.sprouting.personal.model.common.ResultJson;
import com.sprouting.personal.model.common.jsr.AddGroup;
import com.sprouting.personal.model.common.jsr.UpdGroup;
import com.sprouting.personal.model.entity.Dict;
import com.sprouting.personal.model.entity.DictGroup;
import com.sprouting.personal.service.DictGroupService;
import com.sprouting.personal.service.DictService;
import com.sprouting.personal.utils.CheckTool;
import com.sprouting.personal.utils.EntityTool;
import com.sprouting.personal.utils.IdTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 字典 - 字典组
 *
 * @author ：LX（长沙麓谷）
 * @date 创建时间： 2022/7/29 8:40
 */
@RequestMapping("/dict")
@RestController
public class DictController {

    @Autowired
    private DictGroupService dictGroupService;
    @Autowired
    private DictService dictService;


    /**
     * 查询字典-查询公共和当前用户的字典
     * @param page 分页
     * @param dict 字典参数
     * @return
     */
    @PostMapping("/getDictListPage")
    public ResultJson<Page<Dict>> getDictListPage(Page page, Dict dict){
        if (dict == null){
            return ResultJson.errorIllegal();
        }
        if (CheckTool.checkNull(dict.getGroupId())){
            return ResultJson.errorIllegal();
        }

        dict.setUserId(StpUtil.getLoginIdAsString());
        return ResultJson.success(dictService.getDictListPage(page, dict));
    }

    /**
     * 保存字典
     * @param dict 字典
     * @return
     */
    @ApiIdempotent
    @PostMapping("/saveDict")
    public ResultJson<Dict> saveDict(@Validated(AddGroup.class) Dict dict){
        String msg = checkDict(dict);
        if (msg != null){
            return ResultJson.error(msg);
        }

        dict.setId(IdTool.getId());
        // 从这里入口保存的，都是用户的字典
        dict.setUserId(StpUtil.getLoginIdAsString());
        EntityTool.buildSaveBase(dict, StpUtil.getLoginIdAsString());
        dictService.save(dict);
        return ResultJson.success(dict);
    }

    /**
     * 修改字典
     * @param dict 字典
     * @return
     */
    @ApiIdempotent
    @PostMapping("/updDict")
    public ResultJson<Dict> updDict(@Validated(UpdGroup.class) Dict dict){
        String msg = checkDict(dict);
        if (msg != null){
            return ResultJson.error(msg);
        }

        Dict dictDb = dictService.getDictById(dict.getId());
        if (dictDb == null){
            return ResultJson.errorPram();
        }
        if (Constant.BaseData.YES_BASE.equals(dictDb.getBaseData())){
            return ResultJson.error("基础数据不允许修改");
        }

        EntityTool.buildUpdBase(dict, StpUtil.getLoginIdAsString());
        dictService.updateById(dict);
        return ResultJson.success(dict);
    }

    /**
     * 根据字典ID删除字典
     * @param id 字典ID
     * @return
     */
    @ApiIdempotent
    @PostMapping("/delDictById")
    public ResultJson delDictById(String id){
        if (CheckTool.checkNull(id)){
            return ResultJson.errorIllegal();
        }

        Dict dictDb = dictService.getDictById(id);
        if (dictDb == null){
            return ResultJson.errorPram();
        }
        if (!Constant.BaseData.NO.equals(dictDb.getBaseData())){
            return ResultJson.error("基础数据不允许操作");
        }

        dictService.removeById(id);
        return ResultJson.success(null);
    }

    /**
     * 保存字典组
     * @param dictGroup 字典组
     * @return
     */
    @ApiIdempotent
    @PostMapping("/saveDictGroup")
    public ResultJson<DictGroup> saveDictGroup(@Validated(AddGroup.class) DictGroup dictGroup){
        String msg = checkDictGroup(dictGroup);
        if (msg != null){
            return ResultJson.error(msg);
        }

        dictGroup.setId(IdTool.getId());
        // 从这里入口保存的，都是用户的字典
        dictGroup.setUserId(StpUtil.getLoginIdAsString());
        EntityTool.buildSaveBase(dictGroup, StpUtil.getLoginIdAsString());
        dictGroupService.save(dictGroup);
        return ResultJson.success(dictGroup);
    }

    /**
     * 更新字典组
     * @param dictGroup 字典组
     * @return
     */
    @PostMapping("/updDictGroup")
    public ResultJson<DictGroup> updDictGroup(@Validated(UpdGroup.class) DictGroup dictGroup){
        String msg = checkDictGroup(dictGroup);
        if (msg != null){
            return ResultJson.error(msg);
        }

        DictGroup dictGroupDb = dictGroupService.getDictGroupById(dictGroup.getId());
        if (dictGroupDb == null){
            return ResultJson.errorPram();
        }
        if (Constant.BaseData.YES_BASE.equals(dictGroupDb.getBaseData())){
            return ResultJson.error("基础数据不允许修改");
        }

        EntityTool.buildUpdBase(dictGroup, StpUtil.getLoginIdAsString());
        dictGroupService.updateById(dictGroup);
        return ResultJson.success(dictGroup);
    }

    /**
     * 根据ID删除字典组
     * @param id 主键
     * @return
     */
    @PostMapping("/delDictGroupById")
    public ResultJson delDictGroupById(String id){
        if (CheckTool.checkNull(id)){
            return ResultJson.errorIllegal();
        }

        DictGroup dictGroup = dictGroupService.getDictGroupById(id);
        if (dictGroup == null){
            return ResultJson.errorPram();
        }
        if (!Constant.BaseData.NO.equals(dictGroup.getBaseData())){
            return ResultJson.error("基础数据不允许操作");
        }

        List<Dict> dictList = dictService.getDictByGroupId(id, StpUtil.getLoginIdAsString());
        if (CollUtil.isNotEmpty(dictList)){
            if (dictList.stream().anyMatch(obj -> Constant.BaseData.YES_BASE.equals(obj.getBaseData()))){
                return ResultJson.error("字典中存在基础数据");
            }
        }

        List<String> dictIdList = dictList.stream().map(Dict::getId).collect(Collectors.toList());
        dictGroupService.delDictGroupById(dictGroup.getId(), dictIdList);
        return ResultJson.success(null);
    }

    /**
     * 分页查询字典组
     * @param page 分页参数
     * @param dictGroup 字典组参数
     * @return
     */
    @PostMapping("/getDictGroupListPage")
    public ResultJson<Page<DictGroup>> getDictGroupListPage(Page page, DictGroup dictGroup){
        dictGroup.setUserId(StpUtil.getLoginIdAsString());
        return ResultJson.success(dictGroupService.getDictGroupListPage(page, dictGroup));
    }

    /**
     * 检查字典组相关信息 并补全数据
     * @param dictGroup 字典组
     * @return
     */
    private String checkDictGroup(DictGroup dictGroup){
        DictGroup dictGroupDb = dictGroupService.getDictGroupByIdAndCode(dictGroup.getId(), dictGroup.getCode(), StpUtil.getLoginIdAsString());
        if (dictGroupDb != null){
            return "字典组代码已使用";
        }

        // 补全数据
        if (dictGroup.getBaseData() == null){
            dictGroup.setBaseData(Constant.BaseData.NO);
        }
        if (dictGroup.getSort() == null){
            dictGroup.setSort(Constant.DefaultValue.SORT);
        }

        return null;
    }

    /**
     * 检查字典信息，并补全数据
     * @param dict 字典
     * @return
     */
    private String checkDict(Dict dict){
        Dict dictDb = dictService.getDictByGroupIdAndCodeAndId(dict.getId(), dict.getCode(), dict.getGroupId(), StpUtil.getLoginIdAsString());
        if (dictDb != null){
            return "字典代码已使用，同一字典组内代码有且唯一";
        }

        // 补全数据
        if (dict.getBaseData() == null){
            dict.setBaseData(Constant.BaseData.NO);
        }
        if (dict.getSort() == null){
            dict.setSort(Constant.DefaultValue.SORT);
        }

        return null;
    }

}
